package cn.dm.example.syncContainer;

import cn.dm.annoations.NotThreadSafe;

import java.util.Vector;

@NotThreadSafe
public class VectorExample2 {

    private static Vector<Integer> vector = new Vector<>();

    public static void main(String[] args) {

        while (true) {

            for (int i = 0; i < 10; i++) {
                vector.add(i);
            }

            Thread thread1 = new Thread() {
                public void run() {
                    for (int i = 0; i < vector.size(); i++) {
                        vector.remove(i);
                    }
                }
            };

            Thread thread2 = new Thread() {
                public void run() {
                    for (int i = 0; i < vector.size(); i++) {
                        vector.get(i);
                    }
                }
            };
            thread1.start();
            thread2.start();
        }
    }

    /**
     * 不安全原因
     * 比如两个线程同时拿到了 vector.size() = 10
     * thread1把 vector[9] 删了,而 thread2 恰好又去取 vector[9]，
     * 这时就报了线程数组越界异常
     *
     * 由此测例可知，在使用同步容器的时候，也不是所有场景下都能保证线程安全
     */
}
